<template>
  <el-dialog
      v-model="diaVisible"
      :title="title"
      :close-on-click-modal="false"
      :append-to-body="true"
      width="520px"
      @close="resetForm"
  >
    <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
    >
      <el-form-item label="用户角色" prop="role">
        <el-select v-model="ruleForm.role" placeholder="请选择">
          <el-option label="管理员" value="0"/>
          <el-option label="灯具控制员" value="1"/>
          <el-option label="维护人员" value="2"/>
          <el-option label="游客" value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" placeholder="请输入登录密码..."/>
      </el-form-item>
      <el-form-item label="登录密码" prop="passWord">
        <el-input v-model="ruleForm.passWord" placeholder="请输入登录密码..."/>
      </el-form-item>
      <el-form-item label="是否锁定" prop="locked">
        <el-select v-model="ruleForm.locked" placeholder="请选择">
          <el-option label="是" value="1"/>
          <el-option label="否" value="0"/>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div @click="submitForm" class="sure-btn" style="margin-right: 10px">确认</div>
        <div @click="resetForm" class="cancel-btn">取消</div>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {getPublicKey, registerUser} from "../../../router/api.js";
import {passwordEncryption} from "../../../util/index.js";

export default {
  name: "registerUser",
  data() {
    const checkPwd = (rule, value, callback) => {
      const reg = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[^\w\d\s]).{8,}$/;
      if (value === '') {
        callback(new Error('请输入登录密码'))
      } else if (value.length < 8) {
        callback(new Error("密码长度至少8位"))
      } else if (!reg.test(value)) {
        callback(new Error('必须包含字母、数字、符号'))
      } else {
        callback()
      }
    }

    return {
      title: '新增用户',
      diaVisible: false,
      ruleForm: {
        role: '0',
        passWord: '',
        username: '',
        locked: '0'
      },
      ruleFormClone: {},
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        passWord: [
          {required: true, validator: checkPwd, trigger: 'blur'},
        ],
      },
      currentRow: {}
    }
  },
  created() {
    this.ruleFormClone = JSON.parse(JSON.stringify(this.ruleForm))
  },
  methods: {
    show() {
      this.title = '新增用户'
      this.diaVisible = true;
    },
    submitForm() {
      this.$refs['ruleFormRef'].validate(async (valid) => {
        if (valid) {
          let {username, passWord, role, locked} = this.ruleForm
          let resKey = await getPublicKey({username: encodeURIComponent(username)});
          if (resKey.status != 200) {
            // this.$message.warning('获取公钥失败');
            return;
          }
          let encryptedPassword = passwordEncryption(passWord, resKey.data);
          let params = {
            role,
            locked,
            username,
            password: encryptedPassword
          }
          registerUser(params).then(res => {
            if (res.data.code != 200) {
              // this.$message.warning(res.data.msg);
              return;
            } else {
              // this.$message.success(res.data.msg);
              this.resetForm();
              this.$emit('registerOk')
            }
          })
        }
      });
    },
    resetForm() {
      this.diaVisible = false;
      this.ruleForm = this.ruleFormClone;
      this.$refs['ruleFormRef'].resetFields();
    }
  }
}
</script>

<style scoped>

</style>
